﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SchoolManagementSystem.Forms;
using System.IO;
using System.Runtime.InteropServices;

using ActionServices;
using System.Reflection;
using SchoolManagementSystem.Details;
using DevExpress.XtraGrid.Views.Grid;
namespace SchoolManagementSystem.Controls
{
    public partial class MasterMainUC : UserControl
    {
        public MasterMainUC()
        {
            InitializeComponent();
           
        }

        internal protected GridView GridViewMasterUC { get { return gridView1; } }

        bool _isFirstFocus = true;
        string _searchString;
        public DetailUC DetailUCControl
        {
            get
            {
                return _DetailUC;
            }
            set
            {
                try
                {
                    _DetailUC = value;
                    dockPanel1.Controls.Add(_DetailUC);
                    dockPanel1.Text = "Chi tiết " + _DetailUC.ObjectName;
                    _DetailUC.Dock = DockStyle.Fill;
                    _DetailUC.MasterUC = this;

                    this.Text = String.Format("Danh sách {0}", _DetailUC.ObjectName);
                }
                catch { }
            }
        }

        string GridLayout = Application.StartupPath + "\\Layout";
        string DetailLayout = Application.StartupPath + "\\Layout";
        string pathUserLayout = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Jbart\\Layout");
        bool _layoutRestored = false;
        void RestoreLayout()
        {
            if (!_layoutRestored)
            {
                GridLayout = Application.StartupPath + "\\Layout\\" + _DetailUC.GetType().Name + ".GID";
                DetailLayout = Application.StartupPath + "\\Layout\\" + _DetailUC.GetType().Name + ".Detail";
                if (gridView1.RowCount > 0 && File.Exists(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".GID"))
                {
                    gridView1.RestoreLayoutFromXml(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".GID");
                    _layoutRestored = true;
                }
                else
                {      
                    if (gridView1.RowCount > 0 && File.Exists(GridLayout))
                    {
                        gridView1.RestoreLayoutFromXml(GridLayout);
                        _layoutRestored = true;
                    }
                }

                if (File.Exists(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".Detail"))
                {
                    dockManager1.RestoreLayoutFromXml(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".Detail");
                }
                else
                {
                    if (File.Exists(DetailLayout))
                        dockManager1.RestoreLayoutFromXml(DetailLayout);
                }
            }
        }
        public void SaveLayouts()
        {
            try
            {
                gridView1.SaveLayoutToXml(GridLayout);
                dockManager1.SaveLayoutToXml(DetailLayout);

                if (!Directory.Exists(pathUserLayout))
                {
                    Directory.CreateDirectory(pathUserLayout);
                }
                gridView1.SaveLayoutToXml(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".GID");
                dockManager1.SaveLayoutToXml(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".Detail");
                //  _detailControl.SaveLayouts();
            }
            catch (Exception)
            {

            }
        }
        public string SearchString
        {
            get
            {
                return _searchString;
            }
            set
            {
                try
                {
                    _searchString = value;
                    if (_DetailUC != null)
                    {
                        _DetailUC.SearchString = _searchString;
                    }
                    DataBind();
                }
                catch { }
               
            }
        }
       public BaseActionService Model { get; set; }
        public object DataSource { get; set; }
        private IList<object> list = new List<object>();
        DetailUC _DetailUC;

        public int FocusedRow
        {
            get
            {
                return gridView1.FocusedRowHandle;
            }
        }

        public long SelectedID
        {
            get
            {
                try
                {
                    return long.Parse(gridView1.GetRowCellValue(FocusedRow, "ID").ToString());
                }
                catch (Exception)
                {
                    return -1;
                }
            }
        }

        internal bool ReloadData(long ID)
        {
            DataBind();
            int i = 0;

            try
            {
                for (; i < gridView1.RowCount; i++)
                {
                    if ((long)gridView1.GetRowCellValue(i, "ID") == ID)
                    {
                        gridView1.FocusedRowHandle = i;
                    }
                }
            }
            catch (Exception)
            {

                //throw;
            }

            return i < gridView1.RowCount;
        }

        void DataBind()
        {

           
            if (!String.IsNullOrEmpty(_searchString))
            {
                
                gridControl1.DataSource = Model.GetList(_searchString);
                
            }
            else
            {
                gridControl1.DataSource = Model.GetList();
            }
            RestoreLayout();
            gridControl1.RefreshDataSource();
            gridView1.ViewCaption = "Danh sách có " + gridView1.RowCount + " dòng";
            if (Model != null)
            {
                PropertyInfo[] propertyInfos;
                propertyInfos = _DetailUC.Type.GetType().GetProperties();

                foreach (PropertyInfo proInfo in propertyInfos)
                {
                    AttributeCollection attributes = TypeDescriptor.GetProperties(_DetailUC.Type.GetType())[proInfo.Name].Attributes;

                    DescriptionAttribute myAttribute =
                       (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
                    if (String.IsNullOrEmpty(myAttribute.Description))
                    {
                        gridView1.Columns[proInfo.Name].Visible = false;
                    }
                    else
                    {
                        gridView1.Columns[proInfo.Name].Caption = myAttribute.Description;
                        gridView1.Columns[proInfo.Name].OptionsColumn.AllowEdit = false;
                    }
                    SetFormatGridColumn.Format(Model, gridView1, proInfo.Name);
                }

                //if (gridView1.Columns["ID"] != null)
                //{
                //    gridView1.Columns["ID"].Visible = false;

                //    gridView1.Columns["ID"].OptionsColumn.ShowInCustomizationForm = false;
                //}
                gridView1.ExpandAllGroups();

                SetEditAbleGridColumn.SetColumnEditAble(gridView1, "Value", Model);
                SetGroupColumn.SetGroupOperator(Model, gridView1, "Avegare");
                SetGroupColumn.SetGroupOperator(Model, gridView1, "Sum");
                DisplayDetail();
            }
            

            if (_DetailUC.GetType() == typeof(Student_ResultDetailUC))
            {
                barButtonItem_delete.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem_new.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }


        }

        public string SelectedName
        {
            get
            {
                string str = "";

                try
                {
                    str += "[" + (string)gridView1.GetRowCellValue(FocusedRow, "Code") + "]";
                }
                catch (Exception)
                {

                }
                try
                {
                    str += (string)gridView1.GetRowCellValue(FocusedRow, "Name");
                }
                catch (Exception)
                {

                }

                return str;
            }
        }


        protected void Delete()
        {
            if (gridView1.FocusedRowHandle < 0)
                return;

            if (XtraMessageBox.Show(String.Format("{0} {1} sẽ bị xóa khỏi hệ thống, bạn có đồng ý?", _DetailUC.ObjectName, SelectedName), String.Format("Xóa {0}", _DetailUC.ObjectName), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    if (_DetailUC.Delete(SelectedID))
                    {
                        DataBind();
                    }
                    else
                    {
                        XtraMessageBox.Show(String.Format("Bạn phải xóa hết các mẫu tin con của {0} {1}", _DetailUC.ObjectName, SelectedName), String.Format("Lỗi khi xóa {0}", _DetailUC.ObjectName), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception)
                {
                    XtraMessageBox.Show(String.Format("Bạn phải xóa hết các mẫu tin con của {0} {1}", _DetailUC.ObjectName, SelectedName), String.Format("Lỗi khi xóa {0}", _DetailUC.ObjectName), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void Add()
        {
            _DetailUC.DetailAdd();
        }

        void Export()
        {
            SaveFileDialog dlg = new SaveFileDialog();

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                gridView1.ExportToXls(dlg.FileName);
            }
        }
        private bool DisplayDetail()
        {
            if (_DetailUC != null)
            {
                _DetailUC.ID = SelectedID;
                _DetailUC.SearchString = SearchString;

                _DetailUC.Display();

            }

            return true;


        }
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {

            DisplayDetail();
        }

        private void barButtonItem_new_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Add();
        }

        private void barButtonItem_delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Delete();
        }

        private void barButtonItem_refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ReloadData(-1);
        }

        private void barButtonItem_print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.ShowRibbonPrintPreview();
        }

        private void barButtonItem_export_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Export();
        }


        void PressKey(KeyEventArgs e)
        {
            if (e.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.N:
                        _DetailUC.DetailAdd();
                        break;
                    case Keys.S:
                        _DetailUC.DetailSave();
                        break;
                    case Keys.P:
                        gridView1.ShowRibbonPrintPreview();
                        break;
                    case Keys.E:
                        Export();
                        break;
                    //case Keys.Delete: _detailControl.Delete(SelectedID);
                    //    break;
                }
            }

            if (e.KeyCode == Keys.F5)
            {
                ReloadData(-1);
            }
            else if (e.KeyCode == Keys.Delete)
            {
                //_detailControl.Delete(SelectedID);
                Delete();
            }
            else if (e.KeyCode == Keys.F11)
            {
                ShowDetailForm();
            }

        }
         protected void SetupSecurity()
        {
            string tag = DetailUCControl.Code;
            var userrolecheck = frmMain.UserModuleRole.FirstOrDefault(c => c.Module.Equals(tag));
            var grouprolecheck = frmMain.GroupModuleRole.FirstOrDefault(c => c.Module.Equals(tag));

            if ((userrolecheck != null && userrolecheck.Role.Contains("C")) || (grouprolecheck != null && grouprolecheck.Role.Contains("C")))
            {

                barButtonItem_new.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
               
            }
            else
            {
                barButtonItem_new.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                

            }

            if ((userrolecheck != null && userrolecheck.Role.Contains("D")) || (grouprolecheck != null && grouprolecheck.Role.Contains("D")))
            {
                barButtonItem_delete.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                barButtonItem_delete.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            }

            if ((userrolecheck != null && userrolecheck.Role.Contains("P")) || (grouprolecheck != null && grouprolecheck.Role.Contains("P")))
            {
                barButtonItem_print.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                barButtonItem_print.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            }

            if ((userrolecheck != null && userrolecheck.Role.Contains("E")) || (grouprolecheck != null && grouprolecheck.Role.Contains("E")))
            {
                barButtonItem_export.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                barButtonItem_export.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            }

        }

         protected override void OnHandleDestroyed(EventArgs e)
         {
             SaveLayouts();
         }

        void ShowDetailForm()
        {
            frmShowDetailForm frm = new frmShowDetailForm();
           
            frm.ShowDock(null, _DetailUC);
            DetailUCControl = (DetailUC)frm.Control1;
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            PressKey(e);
        }

        private void dockPanel1_KeyDown(object sender, KeyEventArgs e)
        {
            PressKey(e);
        }


        #region RegisterKeyPress

        //----------------------------------------------
        // Define the PeekMessage API call
        //----------------------------------------------

        private struct MSG
        {
            public IntPtr hwnd;
            public int message;
            public IntPtr wParam;
            public IntPtr lParam;
            public int time;
            public int pt_x;
            public int pt_y;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern bool PeekMessage([In, Out] ref MSG msg,
            HandleRef hwnd, int msgMin, int msgMax, int remove);

        //----------------------------------------------

        /// <span class="code-SummaryComment"><summary> </span>
        /// Trap any keypress before child controls get hold of them
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="m">Windows message</param></span>
        /// <span class="code-SummaryComment"><returns>True if the keypress is handled</returns></span>
        protected override bool ProcessKeyPreview(ref Message m)
        {
            const int WM_KEYDOWN = 0x100;
            const int WM_KEYUP = 0x101;
            const int WM_CHAR = 0x102;
            const int WM_SYSCHAR = 0x106;
            const int WM_SYSKEYDOWN = 0x104;
            const int WM_SYSKEYUP = 0x105;
            const int WM_IME_CHAR = 0x286;

            KeyEventArgs e = null;

            if ((m.Msg != WM_CHAR) && (m.Msg != WM_SYSCHAR) && (m.Msg != WM_IME_CHAR))
            {
                e = new KeyEventArgs(((Keys)((int)((long)m.WParam))) | ModifierKeys);
                if ((m.Msg == WM_KEYDOWN) || (m.Msg == WM_SYSKEYDOWN))
                {
                    TrappedKeyDown(e);
                }
                //else
                //{
                //    TrappedKeyUp(e);
                //}

                // Remove any WM_CHAR type messages if supresskeypress is true.
                if (e.SuppressKeyPress)
                {
                    this.RemovePendingMessages(WM_CHAR, WM_CHAR);
                    this.RemovePendingMessages(WM_SYSCHAR, WM_SYSCHAR);
                    this.RemovePendingMessages(WM_IME_CHAR, WM_IME_CHAR);
                }

                if (e.Handled)
                {
                    return e.Handled;
                }
            }
            return base.ProcessKeyPreview(ref m);
        }

        private void RemovePendingMessages(int msgMin, int msgMax)
        {
            if (!this.IsDisposed)
            {
                MSG msg = new MSG();
                IntPtr handle = this.Handle;
                while (PeekMessage(ref msg,
                new HandleRef(this, handle), msgMin, msgMax, 1))
                {
                }
            }
        }

        /// <span class="code-SummaryComment"><summary></span>
        /// This routine gets called if a keydown has been trapped 
        /// before a child control can get it.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="e"></param></span>
        private void TrappedKeyDown(KeyEventArgs e)
        {
            PressKey(e);
        }
 

        #endregion

        private void gridView1_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DetailUCControl.commandBarUC1.cmdsave.Enabled = true;
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DetailUCControl.commandBarUC1.cmdsave.Enabled = true;
        }


    }
}
